using Microsoft.AspNetCore.Mvc;
using System.Text;


namespace Ex01.Controllers {
  public class Math2Controller : Controller {
    public IActionResult Index() {
      
      return View();
    }

    public ContentResult FibonacciWithoutView(uint? n) {
      n = n ?? 2;
      if (n > 1) {
        StringBuilder sb = new StringBuilder("<table border='1'>");
        sb.Append("<tr>");
        uint x = 0, y = 1;
        for (int i = 0; i < n; i++) {
          sb.Append($"<td>{x}</td>");
          y += x;
          x = y - x;
        }
        sb.Append("</tr>");
        sb.Append("</table>");
        return base.Content(sb.ToString(), "text/html");
      } else {
        return base.Content("<h1>Invalid n value!</h1>", "text/html"); 
      }
    }
    public IActionResult FibonacciWithView(uint? n) {
      n = n ?? 2;
      if (n > 1) {
        return View(n);
      } else {
        return View("FibonacciWithViewError"); 
      }
    }

    public ContentResult DTable1(uint nRow=2, uint nColumn=2) {
      StringBuilder sb = new StringBuilder("<table border='1'>");
      sb.Append($"<tr><th colspan='{nColumn}'>Dynamic Table</th></tr>");
      for(var r=0; r<nRow; r++) {
        sb.Append("<tr>");
        for(var c=0; c<nColumn; c++) {
          sb.Append("<td>&nbsp;</td>");
        }
        sb.Append("</tr>");
      }
      sb.Append("</table>");
      return base.Content(sb.ToString(),"text/html");
    }
    //What if we want to reimplement this DTable1 using view approach?
    //Challenge here is how to pass the nRow and nColumn to the view?
    //Basically there are few techniques as listed below:
    //1) Use ViewData
    //2) Use ViewBag
    //3) Use model mapping with new complext type

    //Use ViewData (Based on Dictionary)
    public IActionResult DTable2(uint nRow = 2, uint nColumn = 2) {
      ViewData["nRow"] = nRow;
      ViewData["nColumn"] = nColumn;
      return View();
    }

    //Use ViewBag (Based on Dynamic)
    public IActionResult DTable3(uint nRow = 2, uint nColumn = 2) {
      ViewBag.nRow = nRow;
      ViewBag.nColumn = nColumn;
      return View();
    }

    //Use Model Mapping with custom type
    public IActionResult DTable4(uint nRow = 2, uint nColumn = 2) {
      return View(new Models.Size(nRow, nColumn));
    }

    public IActionResult AggregateResult4Array() {
      int[] data = {1,3,5,7,8,2};
      //return View(data);
      return View("AggregateResult4Collection",data);
    }

    public IActionResult AggregateResult4List() {
      List<int> data = new List<int>(){1,3,5,7,8,2};
      //return View(data);
      return View("AggregateResult4Collection",data);
    }

    public IActionResult SayHello(string userName) {
      //return View(userName);  //This wouldn't work, because userName is view name!
      return View("SayHello", userName);
    }
  }
}
